<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px"
			class="queryForms">
			<el-form-item label="返修任务单" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入返修任务单" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="零件组名称" prop="partName">
				<el-input v-model="queryParams.partName" placeholder="请输入零件组名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="零件组图号" prop="partFigure">
				<el-input v-model="queryParams.partFigure" placeholder="请输入零件组图号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="生产批次" prop="productionBatch">
				<el-input v-model="queryParams.productionBatch" placeholder="请输入生产批次" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="状态" prop="inspectStatus" label-width="70px">
				<el-select v-model="queryParams.inspectStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.inspect_status" :key="dict.value" :label="dict.label"
						:value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['synthesize:store:sinspect:exam']">送检</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleBack"
					v-hasPermi="['synthesize:store:sinspect:back']">退货</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDown"
					v-hasPermi="['synthesize:store:sinspect:issue']">下发</el-button>
			</el-col>
			<CreateForm :ids="ids" :rows="rows" formtype="t_synthesize_store_sinspect" parentId="repairMaterialId" />
			<right-toolbar @changeTableData="changeTableData" menuNames="sinspect59" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns"
				perm="synthesize:store:sinspect:index"></right-toolbar>
		</el-row>

		<!--  -->
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table :key="treetablekey" @expand-change="handleExpandChange" :row-class-name="row_class_name"
				@mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter"
				@cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable"
				@selection-change="handleSelectionChange" lazy :load="loadListDes" ref="table" v-loading="loading"
				:data="EntranceList" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					<template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
					</template>
				</el-table-column>
				<el-table-column label="外协单位" prop="outsourcedUnit" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="返修任务单" prop="repairNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible">
					<template slot-scope="scope">
						<span :style="{ color: scope.row.status == 1 ? 'red' : '#666' }">{{ scope.row.repairNumber
							}}</span>
					</template>
				</el-table-column>
				<el-table-column label="工艺通知单" prop="processNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[2].visible" />
				<el-table-column label="生产批次(3B)" prop="productionBatch" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="状态" align="center" prop="inspectStatus" min-width="100"
					:show-overflow-tooltip="true" v-if="columns[16].visible">
					<template slot-scope="scope">
						<dict-tag :options="dict.type.inspect_status" :value="scope.row.inspectStatus" />
					</template>
				</el-table-column>
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="零件组名称" prop="partName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="零件组图号" prop="partFigure" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[6].visible" />
				<el-table-column label="需求数" prop="partQuantity" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[7].visible" />
				<el-table-column label="领料原因" prop="replacementSituation" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[8].visible" />
				<el-table-column label="验证人" align="center" prop="replacementSituation" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[9].visible">
					<template slot-scope="scope" v-if="!scope.row.hasChildren">
						<el-input v-model="scope.row.verificationName" placeholder="请输入验证人"
							@change="changeEdit(scope.row)" maxlength="20" />
					</template>
				</el-table-column>
				<el-table-column label="发放人" align="center" prop="replacementSituation" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[10].visible">
					<template slot-scope="scope" v-if="!scope.row.hasChildren">
						<el-select v-model="scope.row.grantId" placeholder="请选择发放人" filterable
							@change="changeUser(scope.row, 'grantId', 'grantName', userDown2List)">
							<el-option v-for="user in userDown2List" :key="user.userId" :label="user.nickName"
								:value="user.userId" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="合格证号" align="center" prop="replacementSituation" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[13].visible">
					<template slot-scope="scope" v-if="!scope.row.hasChildren">
						<el-input v-model="scope.row.certificateNumber" placeholder="请输入合格证号"
							@change="changeEdit(scope.row)" maxlength="20" />
					</template>
				</el-table-column>
				<el-table-column label="合格证接收人" align="center" prop="replacementSituation" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[14].visible">
					<template slot-scope="scope" v-if="!scope.row.hasChildren">
						<el-select v-model="scope.row.certificateNumberId" placeholder="请选择合格证接收人" filterable
							@change="changeUser(scope.row, 'certificateNumberId', 'certificateNumberName', userDown4List)">
							<el-option v-for="user in userDown4List" :key="user.userId" :label="user.nickName"
								:value="user.userId" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="缺件备注" align="center" prop="deficiencyRemark" min-width="200"
					:show-overflow-tooltip="true" v-if="columns[15].visible">
					<template slot-scope="scope" v-if="!scope.row.hasChildren">
						<el-input v-model="scope.row.deficiencyRemark" placeholder="请输入" @change="changeEdit(scope.row)"
							maxlength="20" />
					</template>
				</el-table-column>

				<el-table-column label="零件接收人" align="center" prop="partRecipientName" min-width="120"
					:show-overflow-tooltip="true" v-if="columns[17].visible" />
				<el-table-column label="零件接收时间" align="center" prop="partRecipientDate" min-width="120"
					:show-overflow-tooltip="true" v-if="columns[18].visible" />
				<el-table-column label="操作" class-name="small-padding fixed-width" width="122px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)"
								v-hasPermi="['synthesize:store:sinspect:annex']">合格证附件</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)"
								v-hasPermi="['synthesize:store:sinspect:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination64" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改发票对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form1" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="供方" prop="supplier">
					<el-input v-model="form.supplier" placeholder="请输入供方" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="时间" prop="inspectTime">
					<el-date-picker v-model="form.inspectTime" type="date" value-format="yyyy-MM-dd"
						placeholder="请选择时间">
					</el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 下发 -->
		<el-dialog title="下发" :visible.sync="issueopen" width="900px" append-to-body v-dialogDrag>
			<el-form ref="issueform" class="add-form1" :model="issueform" :rules="rules" label-width="120px">
				<el-form-item label="接收人" prop="partRecipientId">
					<el-select v-model="issueform.partRecipientId" placeholder="请选择接收人" filterable>
						<el-option v-for="item in userDown3List" :key="item.userId" :label="item.nickName"
							:value="item.userId">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="接收日期" prop="partRecipientDate">
					<el-date-picker v-model="issueform.partRecipientDate" type="date" value-format="yyyy-MM-dd"
						placeholder="请选择接收日期"> </el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitIssueForm">确 定</el-button>
				<el-button @click="issueopen = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listEntrance, listEntranceChild, submitEntrance, delEntrance, handleEntranceIn, handleEntranceBack, handleEntranceDown, repairMaterialPart } from "@/api/synthesize/store/sinspect"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import ProductPlan from "@/views/components/ProductPlan"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import CreateForm from "@/views/components/CreateForm"
import { mapGetters } from "vuex"
import { getUserList, getcolumn, userDown2, userDown3, userDown4 } from "@/api/selectList"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'
export default {
	mixins: [searchStateMixin],   
	name: "Sinspect",
	dicts: ["default_approve", "product_intact_state", "inspect_status"],
	components: { ApproveTemplete, ProductPlan, RecordsTemplete, CreateForm },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			tableTreeRefreshTool: {}, // 用于存储 resolve 方法和展开状态
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			hoverRowIndex: -1, // 鼠标悬停的行索引
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			EntranceList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				inspectStatus: undefined,
				applyTime: undefined,
				repairNumber: undefined,
				partName: undefined,
				partFigure: undefined,
				productionBatch: undefined,
				productModel: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				supplier: [{ required: true, message: "请输入供方", trigger: "blur" }],
				inspectTime: [{ required: true, message: "请输入时间", trigger: "blur" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 生产计划
			isOne: false,
			disabled: false,
			// 审批流程
			openRecords: false,
			approveRecord: [],
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `外协单位`, visible: true },
				{ key: 1, label: `返修任务单`, visible: true },
				{ key: 2, label: `工艺通知单`, visible: true },
				{ key: 3, label: `生产批次(3B)`, visible: true },
				{ key: 4, label: `产品型号`, visible: true },
				{ key: 5, label: `零件组名称`, visible: true },
				{ key: 6, label: `零件组图号`, visible: true },
				{ key: 7, label: `需求数`, visible: true },
				{ key: 8, label: `领料原因`, visible: true },
				{ key: 9, label: `验证人`, visible: true },
				{ key: 10, label: `发放人`, visible: true },
				{ key: 11, label: `接收人`, visible: true },
				{ key: 12, label: `接收日期`, visible: true },
				{ key: 13, label: `合格证号`, visible: true },
				{ key: 14, label: `合格证接收人`, visible: true },
				{ key: 15, label: `缺件备注`, visible: true },
				{ key: 16, label: `状态`, visible: true },
				{ key: 17, label: `零件接收人`, visible: true },
				{ key: 18, label: `零件接收时间`, visible: true }
			],
			userList: [],
			// 下发
			issueopen: false,
			issueform: {},
			userDown4List: [],
			userDown3List: [],
			userDown2List: []
		}
	},

	created() {
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			this.resetForm("queryForm")
			// 清除URL中的查询参数（不刷新页面）
			window.history.replaceState({}, document.title, window.location.pathname);
		}
		this.getuserDown4()
		this.getuserDown3()
		this.getuserDown2()
		// this.getSize()
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetQuerys()
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				}this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		// 选中事件
		handleSelect(selection, row) {
			if (row.hasChildren) {
				// 父级被选中时，递归选中子级
				this.setChildrenSelection(row, true)
			}
		},
		// 全选事件
		handleSelectAll(selection) {
			this.EntranceList.forEach(item => {
				this.setChildrenSelection(item, selection.length > 0)
			})
		},
		// 递归设置子级选中状态
		setChildrenSelection(row, isSelect) {
			this.$refs.table.toggleRowSelection(row, isSelect)
			console.log(row.children, "row.children")
			if (row.children && row.children.length > 0) {
				row.children.forEach(child => {
					this.setChildrenSelection(child, isSelect)
				})
			}
		},
		getuserDown4() {
			userDown4().then(res => {
				this.userDown4List = res.rows
			})
		},
		getuserDown3() {
			userDown3().then(res => {
				this.userDown3List = res.rows
			})
		},
		getuserDown2() {
			userDown2().then(res => {
				this.userDown2List = res.rows
			})
		},
		getSize() {
			getcolumn({ pageName: "Pagination64" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		handleMouseMove(event, row, column) {
			// 获取当前行的索引
			const rowIndex = this.EntranceList.indexOf(row)
			if (rowIndex !== this.hoverRowIndex) {
				this.hoverRowIndex = rowIndex
				// 勾选当前行的复选框
				if (row.checked === false) {
					this.$refs.myTable.toggleRowSelection(row, true)
				}
			}
		},
		handleMouseLeave() {
			// 鼠标离开表格时重置悬停行索引
			this.hoverRowIndex = -1
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 获取用户下拉列表
		async getUserList() {
			let ret = await getUserList()
			this.userList = ret.rows
		},
		// 更改用户
		changeUser(row, id, name, list) {
			let cur = list.find(ele => {
				return ele.userId == row[id]
			})
			row[name] = cur.nickName
			this.changeEdit(row)
		},
		// 提交修改
		changeEdit(row) {
			let data = {
				id: row.id.replace("c", ""),
				verificationId: row.verificationId || undefined,
				verificationName: row.verificationName || undefined,
				grantId: row.grantId || undefined,
				grantName: row.grantName || undefined,
				receiveId: row.receiveId || undefined,
				receiveName: row.receiveName || undefined,
				certificateNumberTime: row.certificateNumberTime || undefined,
				certificateNumber: row.certificateNumber || undefined,
				certificateNumberId: row.certificateNumberId || undefined,
				certificateNumberName: row.certificateNumberName || undefined,
				deficiencyRemark: row.deficiencyRemark || undefined //缺件备注
			}
			repairMaterialPart(data).then(response => {
				this.$modal.msgSuccess("操作成功")
			})
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listEntrance(this.queryParams).then(response => {
				this.EntranceList = response.rows
				this.EntranceList.length > 0 &&
					this.EntranceList.forEach((item, index) => {
						item.hasChildren = true
						item.sort = index + 1
						item.isSelect = false
					})
				this.total = response.total
				this.loading = false
			})
		},
		refreshLoadTree(parentId) {
			const { tree, treeNode, resolve } = this.treeMap.get(parentId)
			this.loadListDes(tree, treeNode, resolve) // 重新加载子级数据
			this.$refs.table.clearSelection()
		},
		// 关闭所有展开的行
		closeAllExpansions() {
			this.EntranceList.forEach(row => {
				this.$refs.table.toggleRowExpansion(row, false)
			})
			this.getList()
			this.$refs.table.clearSelection()
		},
		// 展开/收起时触发
		handleExpandChange(row, expanded) {
			const curr = this.tableTreeRefreshTool[row.id]
			if (!curr) return
			curr.expandCount++
			if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
				let queryParams = JSON.parse(JSON.stringify(this.queryParams))
				delete queryParams.pageSize
				delete queryParams.pageNum
				listEntranceChild({
					repairMaterialId: row.id,
					...queryParams
				}).then(res => {
					res.rows.forEach((item, index) => {
						// 父子id会冲突
						item.id = "c" + item.id
						item.sort = index + 1
					})
					curr.resolve(res.rows)
				})
			}
			curr.prevStatus = expanded
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, { tree: tree, treeNode, resolve })
			}
			this.tableTreeRefreshTool[tree.id] = {
				resolve,
				expandCount: 0, // 展开次数
				prevStatus: false // 上一次的展开状态
			}
			let queryParams = JSON.parse(JSON.stringify(this.queryParams))
			delete queryParams.pageSize
			delete queryParams.pageNum
			let data = {
				repairMaterialId: tree.id,
				...queryParams
			}
			let ret = await listEntranceChild(data)
			tree.hasChildren = ret.rows.length > 0
			tree.children = ret.rows
			if (ret.rows.length == 0) {
				resolve([]) // 确保返回空数组
				this.$set(this.$refs.table.store.states.lazyTreeNodeMap, tree.id, [])
			} else {
				ret.rows.forEach((item, index) => {
					item.id = "c" + item.id
					item.sort = index + 1
				})
				resolve(ret.rows)
			}
		},
		// 取消按钮
		cancel() {
			this.$refs.table.clearSelection()
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				ids: undefined,
				supplier: undefined,
				inspectTime: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.closeAllExpansions()
			this.saveSearchState() 
			this.getList()
			this.treetablekey = Math.random()
		},
		resetQuerys() {
			this.resetForm("queryForm")
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				deviceName: undefined,
				inspectStatus: undefined,
				applyTime: undefined,
				repairNumber: undefined,
				partName: undefined,
				partFigure: undefined,
				productionBatch: undefined,
				productModel: undefined
			}
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				deviceName: undefined,
				inspectStatus: undefined,
				applyTime: undefined,
				repairNumber: undefined,
				partName: undefined,
				partFigure: undefined,
				productionBatch: undefined,
				productModel: undefined
			}
			this.clearSearchCache()
			this.handleQuery()
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
				let flag = this.ids.some(item => item == row.id)
				if (row.hasChildren) {
					row.children.forEach(items => {
						if (flag) {
							this.$refs.table.toggleRowSelection(items, true)
						}
					})
				}
			}
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},

		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		checkIds() {
			// 判断ids
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			let ids = this.ids.map(item => {
				return item.replace("c", "")
			})
			return ids
		},
		/** 送检操作 */
		handleAdd() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = true
			this.rows.forEach(item => {
				if (item.inspectStatus == "1" || item.inspectStatus == "0" || item.inspectStatus == "4" || item.inspectStatus == "2") {
					checkrows = false
				}
			})
			let flag = this.rows.every(item => item.repairMaterialId == this.rows[0].repairMaterialId)
			if (!flag) {
				this.$modal.msg("只能选择相同父级数据")
				return false
			}
			if (checkrows) {
				this.$modal.msg("只有已入库、待入库、退货和不合格数据可以送检")
				return false
			}
			this.reset()
			this.form.ids = ids
			this.open = true
			this.title = "送检"
		},
		// 入库
		handleIn() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "0" && item.inspectStatus != "2") {
					checkrows = true
				}
			})
			if (checkrows) {
				this.$modal.msg("只有待入库和退货可以入库")
				return false
			}
			this.$modal
				.confirm("是否确认入库数据项？")
				.then(function () {
					return handleEntranceIn(ids)
				})
				.then(() => {
					this.$modal.msgSuccess("入库成功")
					this.closeAllExpansions()
				})
				.catch(() => { })
		},
		// 退货
		handleBack() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "1" && item.inspectStatus != "4") {
					checkrows = true
				}
			})
			if (checkrows) {
				this.$modal.msg("只有入库和不合格可以退货")
				return false
			}
			// 退货操作
			this.$modal
				.confirm("是否确认退货数据项？")
				.then(function () {
					return handleEntranceBack(ids)
				})
				.then(() => {
					this.closeAllExpansions()
					this.$modal.msgSuccess("退货成功")
				})
				.catch(() => { })
		},
		issueReset() {
			this.issueform = {
				ids: undefined,
				partRecipientId: undefined,
				partRecipientName: undefined,
				partRecipientDate: undefined
			}
			this.resetForm("issueform")
		},
		// 下发
		handleDown() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "1" && item.inspectStatus != "3" && item.inspectStatus != "5") {
					checkrows = true
				}
			})
			console.log(checkrows)
			if (checkrows) {
				this.$modal.msg("只有入库、合格、让步接收可以下发")
				return false
			}
			// 下发操作
			this.issueReset()
			this.issueform.ids = ids
			this.issueopen = true
		},
		// 下发
		submitIssueForm() {
			this.$refs["issueform"].validate(valid => {
				if (valid) {
					// 接收人姓名
					let cur = this.userDown3List.find(item => {
						return item.userId == this.issueform.partRecipientId
					})
					this.issueform.partRecipientName = cur.nickName
					const loading = this.$loading({
						lock: true,
						text: "Loading",
						spinner: "el-icon-loading",
						background: "rgba(0, 0, 0, 0.7)"
					})
					handleEntranceDown(this.issueform)
						.then(response => {
							this.$modal.msgSuccess("操作成功")
							this.issueopen = false
							loading.close()
							localStorage.setItem("todoMessage", "sinspect2")
							this.closeAllExpansions()
						})
						.finally(() => {
							loading.close()
						})
				}
			})
		},
		/** 修改按钮操作 */
		// handleUpdate(row) {
		//   this.reset();
		//   const id = row.id || this.ids;
		//   getEntrance(id).then((response) => {
		//     this.form = response.data;
		//     this.open = true;
		//     this.title = "修改设备保养计划";
		//   });
		// },
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					submitEntrance(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						localStorage.setItem("todoMessage", "sinspect1")
						this.closeAllExpansions()
					})
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delEntrance(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
					this.$refs.table.clearSelection()
				})
				.catch(() => { })
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id,
				workflowType: "5"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		// 关闭更改保养计划
		cancelChange() {
			this.changeOpen = false
		},
		// 工艺流程列表
		showTechnologyList() {
			return false
			alert("工艺流程列表")
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 39,
					perm: "synthesize:store:sinspect:annex",
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/synthesize/sinspect"
				}
			})
		},
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 40,
					perm: "synthesize:store:sinspect:annex2",
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/synthesize/sinspect"
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 122px !important;
}
</style>
